using Microsoft.AspNetCore.Mvc;
using JGSY.CMS.LowCode.Platform.Infrastructure.Services.Search;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 搜索控制器
    /// 提供全局搜索和实体搜索功能
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class SearchController : ControllerBase
    {
        private readonly ISearchService _searchService;
        private readonly ILogger<SearchController> _logger;

        public SearchController(
            ISearchService searchService,
            ILogger<SearchController> logger)
        {
            _searchService = searchService ?? throw new ArgumentNullException(nameof(searchService));
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// 全局搜索
        /// </summary>
        /// <param name="q">搜索关键词</param>
        /// <param name="entityTypes">实体类型过滤器（可选）</param>
        /// <param name="categories">分类过滤器（可选）</param>
        /// <param name="tags">标签过滤器（可选）</param>
        /// <param name="page">页码（从0开始）</param>
        /// <param name="size">每页大小</param>
        /// <returns>搜索结果</returns>
        [HttpGet]
        public async Task<ActionResult<SearchResultDto>> Search(
            [FromQuery] string q,
            [FromQuery] string[]? entityTypes = null,
            [FromQuery] string[]? categories = null,
            [FromQuery] string[]? tags = null,
            [FromQuery] int page = 0,
            [FromQuery] int size = 20)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(q))
                {
                    return BadRequest("搜索关键词不能为空");
                }

                if (size > 100)
                {
                    size = 100; // 限制最大页面大小
                }

                var filters = new SearchFiltersDto();
                
                if (entityTypes?.Length > 0)
                    filters.EntityTypes = entityTypes.ToList();
                
                if (categories?.Length > 0)
                    filters.Categories = categories.ToList();
                
                if (tags?.Length > 0)
                    filters.Tags = tags.ToList();

                var result = await _searchService.GlobalSearchAsync(q, filters, page, size);
                
                _logger.LogInformation("全局搜索完成，关键词: {Keyword}, 结果数量: {Count}", q, result.TotalCount);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "全局搜索失败，关键词: {Keyword}", q);
                return StatusCode(500, "搜索服务暂时不可用");
            }
        }

        /// <summary>
        /// 按实体类型搜索
        /// </summary>
        /// <param name="entityType">实体类型</param>
        /// <param name="q">搜索关键词</param>
        /// <param name="categories">分类过滤器（可选）</param>
        /// <param name="tags">标签过滤器（可选）</param>
        /// <param name="status">状态过滤器（可选）</param>
        /// <param name="author">作者过滤器（可选）</param>
        /// <param name="page">页码（从0开始）</param>
        /// <param name="size">每页大小</param>
        /// <returns>搜索结果</returns>
        [HttpGet("{entityType}")]
        public async Task<ActionResult<SearchResultDto>> SearchByEntityType(
            string entityType,
            [FromQuery] string q,
            [FromQuery] string[]? categories = null,
            [FromQuery] string[]? tags = null,
            [FromQuery] string[]? status = null,
            [FromQuery] string[]? author = null,
            [FromQuery] int page = 0,
            [FromQuery] int size = 20)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(q))
                {
                    return BadRequest("搜索关键词不能为空");
                }

                if (string.IsNullOrWhiteSpace(entityType))
                {
                    return BadRequest("实体类型不能为空");
                }

                if (size > 100)
                {
                    size = 100; // 限制最大页面大小
                }

                var filters = new SearchFiltersDto();
                
                if (categories?.Length > 0)
                    filters.Categories = categories.ToList();
                
                if (tags?.Length > 0)
                    filters.Tags = tags.ToList();
                
                if (status?.Length > 0)
                    filters.Statuses = status.ToList();
                
                if (author?.Length > 0)
                    filters.Authors = author.ToList();

                var result = await _searchService.SearchByEntityTypeAsync(entityType, q, filters, page, size);
                
                _logger.LogInformation("实体类型搜索完成，类型: {EntityType}, 关键词: {Keyword}, 结果数量: {Count}", 
                    entityType, q, result.TotalCount);
                
                return Ok(result);
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning(ex, "实体类型搜索参数错误，类型: {EntityType}", entityType);
                return BadRequest(ex.Message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "实体类型搜索失败，类型: {EntityType}, 关键词: {Keyword}", entityType, q);
                return StatusCode(500, "搜索服务暂时不可用");
            }
        }

        /// <summary>
        /// 获取搜索建议
        /// </summary>
        /// <param name="q">关键词前缀</param>
        /// <param name="maxCount">最大建议数量</param>
        /// <returns>搜索建议列表</returns>
        [HttpGet("suggestions")]
        public async Task<ActionResult<IEnumerable<string>>> GetSuggestions(
            [FromQuery] string q,
            [FromQuery] int maxCount = 10)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(q) || q.Length < 2)
                {
                    return BadRequest("搜索关键词长度至少为2个字符");
                }

                if (maxCount > 50)
                {
                    maxCount = 50; // 限制最大建议数量
                }

                var suggestions = await _searchService.GetSearchSuggestionsAsync(q, maxCount);
                
                return Ok(suggestions);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取搜索建议失败，关键词: {Keyword}", q);
                return StatusCode(500, "搜索建议服务暂时不可用");
            }
        }

        /// <summary>
        /// 高级搜索
        /// </summary>
        /// <param name="request">高级搜索请求</param>
        /// <returns>搜索结果</returns>
        [HttpPost("advanced")]
        public async Task<ActionResult<SearchResultDto>> AdvancedSearch([FromBody] AdvancedSearchRequest request)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(request.Keyword))
                {
                    return BadRequest("搜索关键词不能为空");
                }

                if (request.PageSize > 100)
                {
                    request.PageSize = 100; // 限制最大页面大小
                }

                var filters = new SearchFiltersDto
                {
                    EntityTypes = request.EntityTypes,
                    Categories = request.Categories,
                    Tags = request.Tags,
                    Statuses = request.Statuses,
                    Authors = request.Authors,
                    CreatedDateRange = request.CreatedDateRange,
                    UpdatedDateRange = request.UpdatedDateRange,
                    CustomFilters = request.CustomFilters
                };

                SearchResultDto result;
                
                if (request.EntityTypes?.Count == 1)
                {
                    // 单个实体类型搜索
                    result = await _searchService.SearchByEntityTypeAsync(
                        request.EntityTypes.First(), 
                        request.Keyword, 
                        filters, 
                        request.PageIndex, 
                        request.PageSize);
                }
                else
                {
                    // 全局搜索
                    result = await _searchService.GlobalSearchAsync(
                        request.Keyword, 
                        filters, 
                        request.PageIndex, 
                        request.PageSize);
                }
                
                _logger.LogInformation("高级搜索完成，关键词: {Keyword}, 结果数量: {Count}", 
                    request.Keyword, result.TotalCount);
                
                return Ok(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "高级搜索失败，关键词: {Keyword}", request?.Keyword);
                return StatusCode(500, "搜索服务暂时不可用");
            }
        }

        /// <summary>
        /// 重建搜索索引
        /// </summary>
        /// <param name="entityType">实体类型（可选，为空则重建所有索引）</param>
        /// <returns>重建结果</returns>
        [HttpPost("rebuild-index")]
        public async Task<ActionResult<object>> RebuildIndex([FromQuery] string? entityType = null)
        {
            try
            {
                _logger.LogInformation("开始重建搜索索引，实体类型: {EntityType}", entityType ?? "全部");
                
                var success = await _searchService.RebuildIndexAsync(entityType);
                
                if (success)
                {
                    _logger.LogInformation("搜索索引重建成功，实体类型: {EntityType}", entityType ?? "全部");
                    return Ok(new { success = true, message = "索引重建成功" });
                }
                else
                {
                    _logger.LogWarning("搜索索引重建失败，实体类型: {EntityType}", entityType ?? "全部");
                    return StatusCode(500, new { success = false, message = "索引重建失败" });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重建搜索索引异常，实体类型: {EntityType}", entityType);
                return StatusCode(500, new { success = false, message = "索引重建服务暂时不可用" });
            }
        }
    }

    /// <summary>
    /// 高级搜索请求
    /// </summary>
    public class AdvancedSearchRequest
    {
        /// <summary>
        /// 搜索关键词
        /// </summary>
        public string Keyword { get; set; } = string.Empty;

        /// <summary>
        /// 实体类型过滤器
        /// </summary>
        public List<string>? EntityTypes { get; set; }

        /// <summary>
        /// 分类过滤器
        /// </summary>
        public List<string>? Categories { get; set; }

        /// <summary>
        /// 标签过滤器
        /// </summary>
        public List<string>? Tags { get; set; }

        /// <summary>
        /// 状态过滤器
        /// </summary>
        public List<string>? Statuses { get; set; }

        /// <summary>
        /// 作者过滤器
        /// </summary>
        public List<string>? Authors { get; set; }

        /// <summary>
        /// 创建时间范围过滤器
        /// </summary>
        public DateRangeFilter? CreatedDateRange { get; set; }

        /// <summary>
        /// 更新时间范围过滤器
        /// </summary>
        public DateRangeFilter? UpdatedDateRange { get; set; }

        /// <summary>
        /// 自定义属性过滤器
        /// </summary>
        public Dictionary<string, object>? CustomFilters { get; set; }

        /// <summary>
        /// 页码（从0开始）
        /// </summary>
        public int PageIndex { get; set; } = 0;

        /// <summary>
        /// 每页大小
        /// </summary>
        public int PageSize { get; set; } = 20;
    }
}
